<!-- Copyright (c) 2022 渝州大数据实验室
 *
 * Lanius is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *
 *     http://license.coscl.org.cn/MulanPSL2
 *
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
-->
<!-- 
* @desc:用户管理
* @fileName:UserManage.vue
* @author:chenxiaofeng@yzbdl.ac.cn
* @date:2022-4-7
!-->
<script setup lang="ts">
import { onMounted, reactive } from "vue";
import UserSearch from "./components/user-search.vue";
import UserDetails from "./components/user-details.vue";
import UserPagination from "@/components/common/pagination.vue";
import OperationDialog from "./components/operation.vue";
import { idToAccount } from "@/common/util/idToAccount";
import { showSuccessMessage, showErrorMessage } from "@/common/message";
import { getCurrentInstance } from "vue";
const { proxy } = getCurrentInstance() as any;

const listData = reactive({
  // 列表数据
  tableData: [],
  // 列表总数
  total: 0,
  // 列表加载动画
  isListLoading: false,
  // 查询加载动画
  isSearchLoading: false,
  // 弹窗标识
  opDialog: false,
  // 角色列表数据
  roleList: [],
  // 弹窗标题
  addOrEdit: "",
  // 修改用户所存当前行数据
  oneUserInfo: {},
  isPageLoading: null as any, //页面加载使用变量
});

/**
 * 定义请求数据
 */
let reqData = {
  nickName: "",
  userName: "",
  page: 1,
};

/**
 * 获取列表
 * @reture viod
 */
const reqTableList = () => {
  listData.isListLoading = true;
  const result = proxy.$HTTP.post({
    url: `/user/query`,
    params: {
      page: reqData.page,
      size: 10,
    },
    data: {
      nickName: reqData.nickName,
      userName: reqData.userName,
    },
  });
  result
    .then((res: any) => {
      if (res.isOk) {
        let listArray = res.data.records;
        if (res.data.records.length > 0) {
          listData.isPageLoading = true;
        } else {
          listData.isPageLoading = false;
        }
        const ids = res.data.records.map((item: any) => {
          return item.createId;
        });
        let newId = Array.from(new Set(ids));
        const creaters = idToAccount(newId);
        creaters.then((res: any) => {
          if (res.isOk === true) {
            const ids = res.data;
            const idsMap: any = {};
            ids.forEach((id: any) => {
              idsMap[id.id] = id.nickName;
            });
            listData.tableData = listArray.map((m: any) => {
              m.createId = idsMap[m.createId]
                ? idsMap[m.createId]
                : "用户已被删除";
              return m;
            });
          }
        });
        listData.total = Number(res.data.total);
      }
      listData.isListLoading = false;
      listData.isSearchLoading = false;
    })
    .catch((response: any) => {
      showErrorMessage({ message: response.data });
      listData.isListLoading = false;
      listData.isSearchLoading = false;
    });
};

/**
 * 查询方法
 * @param filter 查询条件对象
 * @reture viod
 */
const searchFunc = (filter: any) => {
  listData.isSearchLoading = true;
  // 查询方法实现
  reqData.nickName = filter.nickValue;
  reqData.userName = filter.userValue;
  reqTableList();
};

/**
 * 根据页码跳转页面
 * @param pageNumber 页码
 * @reture viod
 */
const getCurrentPageNumber = (pageNumber: number) => {
  reqData.page = pageNumber;
  reqTableList();
};

/**
 * 打开新增弹窗
 * @reture viod
 */
const dialogControlFunc = () => {
  listData.addOrEdit = "新增";
  listData.oneUserInfo = {};
  listData.opDialog = true;
};

/**
 * 编辑弹窗控制
 * @param oneInfo 当前行数据值
 * @reture viod
 */
const dialogEditFunc = (oneInfo: any) => {
  listData.addOrEdit = "编辑";
  listData.oneUserInfo = { ...oneInfo };
  listData.opDialog = true;
};

/**
 * 获取所属角色
 * @reture viod
 */
const getRoleList = () => {
  const res = proxy.$HTTP.get({
    url: `/role`,
  });
  res
    .then((res: any) => {
      if (res.isOk) {
        listData.roleList = res.data;
      }
    })
    .catch((response: any) => {
      showErrorMessage({ message: response.data });
    });
};

/**
 * 新增用户
 * @param userInfo 新增用户的信息
 * @reture viod
 */
const saveUser = (userInfo: any) => {
  //保存方法实现
  const res = proxy.$HTTP.post({
    url: `/user`,
    data: userInfo,
  });
  res
    .then((res: any) => {
      if (res.code === 200) {
        showSuccessMessage({
          message: "保存成功！",
        });
        listData.opDialog = false;
        reqTableList();
      }
    })
    .catch((response: any) => {
      console.log(response);
      if (response.code != 2001) {
        listData.opDialog = false;
      }
      showErrorMessage({ message: response.data });
    });
};

/**
 * 修改用户
 * @param userInfo 修改用户的信息
 * @reture viod
 */
const editUser = (userInfo: any) => {
  const res = proxy.$HTTP.put({
    url: `/user`,
    data: userInfo,
  });
  res
    .then((res: any) => {
      if (res.code === 200) {
        showSuccessMessage({
          message: "修改成功！",
        });
        listData.opDialog = false;
        reqTableList();
      }
    })
    .catch((response: any) => {
      listData.opDialog = false;
      showErrorMessage({ message: response.data });
    });
};

/**
 * 删除用户
 * @param id 用户ID
 * @reture viod
 */
const delUser = (id: string) => {
  const res = proxy.$HTTP.delete({
    url: `/user/` + id,
  });
  res
    .then((res: any) => {
      if (res.code === 200) {
        showSuccessMessage({
          message: "删除成功！",
        });
        listData.opDialog = false;
        reqTableList();
      }
    })
    .catch((response: any) => {
      listData.opDialog = false;
      showErrorMessage({ message: response.data });
    });
};

/**
 * 改变单个用户状态
 * @param v 改变的状态值
 * @param r 当前行数据
 * @reture viod
 */
const changeStatus = (v: any, r: any) => {
  const res = proxy.$HTTP.post({
    url: `/user/` + r.id + "/status",
    data: {
      status: v,
    },
  });
  res
    .then((res: any) => {
      if (res.code === 200) {
        let msg: string = "";
        if (v === 1) {
          msg = "启用成功";
        } else {
          msg = "禁用成功";
        }
        showSuccessMessage({
          message: msg,
        });
        listData.opDialog = false;
        reqTableList();
      }
    })
    .catch((response: any) => {
      listData.opDialog = false;
      showErrorMessage({
        message: response.data,
      });
    });
};

onMounted(() => {
  // 初始化列表数据
  reqTableList();
  // 获取角色列表
  getRoleList();
});
</script>

<template>
  <div class="page-list">
    <!-- 表单 -->
    <div class="page-table">
      <!-- 查询 -->
      <user-search
        :searchFunc="searchFunc"
        :isSearchLoading="listData.isSearchLoading"
        :dialogControlFunc="dialogControlFunc"
      ></user-search>
      <!-- 列表详情 -->
      <user-details
        :delUser="delUser"
        :isPageLoading="listData.isPageLoading"
        :dialogEditFunc="dialogEditFunc"
        :changeStatus="changeStatus"
        :tableData="listData.tableData"
        :isListLoading="listData.isListLoading"
      ></user-details>
      <!-- 分页 -->
      <user-pagination
        :total="listData.total"
        :getCurrentPageNumber="getCurrentPageNumber"
      ></user-pagination>
    </div>
  </div>
  <!-- 新增弹窗 -->
  <el-dialog
    v-model="listData.opDialog"
    v-if="listData.opDialog"
    :title="listData.addOrEdit"
    :width="740"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <operation-dialog
      :roleList="listData.roleList"
      :addOrEdit="listData.addOrEdit"
      :saveUser="saveUser"
      :editUser="editUser"
      :oneUserInfo="listData.oneUserInfo"
    />
  </el-dialog>
</template>

<style lang="scss" scoped>
.page-list {
  background-color: #fff;
  position: relative;
  padding: 15px;
  height: calc(100vh - 130px);
}
</style>
